package dav.mobile.garuda.states.scene;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

import com.badlogic.gdx.Files.FileType;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.g2d.TextureRegion;

import dav.mobile.garuda.components.ResourceManager;

public class Scene {
	public String m_Text;
	public String m_Name;
	public TextureRegion m_Right;
	public TextureRegion m_Left;
	
	public Scene(String text, String name, String right, String left) {
		m_Text = text;
		m_Name = name;
		
		m_Left = ResourceManager.GetVNFromString(left);
		
		//copy and flip
		m_Right = ResourceManager.GetVNFromString(right);
		if (m_Right!=null) {
			m_Right = new TextureRegion(m_Right);
			m_Right.flip(true, false);
		}
	}
	
	public void Dispose() {
		m_Text = null;
		m_Right = null;
		m_Left = null;
	}
	
	public static Queue<Scene> CreateScene(String m_Path) {
		Queue<Scene> m_Scenes = new LinkedList<Scene>();
		
		File m_File = new File(m_Path);
		FileHandle m_Handler = new FileHandle(m_File, FileType.Internal) {
			
			@Override
			public FileHandle parent() {
				return null;
			}
			
			@Override
			public FileHandle child(String arg0) {
				return null;
			}
		};
		
		try {
			BufferedReader m_Reader = new BufferedReader(new StringReader(m_Handler.readString()));
			
			String m_Line = m_Reader.readLine();
			while (m_Line!=null) {
				//Get Character
				StringTokenizer m_Token = new StringTokenizer(m_Line);
				String left = (String) m_Token.nextElement();
				String right = (String) m_Token.nextElement();
				
				//Get Name
				m_Line = m_Reader.readLine();
				String name = m_Line;
				
				//Get Text
				StringBuffer m_Buffer = new StringBuffer();
				m_Line = m_Reader.readLine();
				if (m_Line!=null) {
					m_Buffer.append(m_Line);
					m_Buffer.append("\n");
				}
				
				m_Line = m_Reader.readLine();
				if (m_Line!=null) {
					m_Buffer.append(m_Line);
					m_Buffer.append("\n");
				}
				
				m_Line = m_Reader.readLine();
				if (m_Line!=null) {
					m_Buffer.append(m_Line);
					m_Buffer.append("\n");
				}
				
				String text = m_Buffer.toString();
				
				//System.out.println(text);
				
				//Add to scenes
				Scene m_Scene = new Scene(text, name, right, left);
				m_Scenes.add(m_Scene);
				
				//Iterate
				m_Line = m_Reader.readLine();
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		
		return m_Scenes;
	}
}
